/**
 * 
 */
package moviles.turnomovil.mundo;

import java.util.Calendar;

import moviles.turnomovil.interfaz.VerTurnoActivity;


import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * Este servicio es lanzado cuando se toma un turno
 * @author administrator
 *
 */
public class AlertaService extends Service {

	private static final int ALERT_ID = 1;

	private Calendar tiempoEstimado;
	
	private Alerta[] alertas;
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		tiempoEstimado = TurnoMovil.getInstance().getTiempoEstimado();
		alertas = TurnoMovil.getInstance().getAlertas();
		Thread thr = new Thread(null, task, "AlertaService");
		thr.start();
	}
	
	public Runnable task = new Runnable() {
		
		public void run() 
		{
			while((tiempoEstimado.getTimeInMillis() - System.currentTimeMillis()) >= 0) {
				tiempoEstimado = TurnoMovil.getInstance().getTiempoEstimado();
				alertas = TurnoMovil.getInstance().getAlertas();
				for( int i= 0 ; i < alertas.length; i++ ){
					if(alertas[i] != null) {
						if( (tiempoEstimado.getTimeInMillis() - System.currentTimeMillis()) <= alertas[i].getTiempo() ) {
							Log.d("Alerta", "  "+ (tiempoEstimado.getTimeInMillis() - System.currentTimeMillis()));
							crearNotificacion(alertas[i].getTiempo(), alertas[i].isSonido(), alertas[i].isVibrar() );
							TurnoMovil.getInstance().removeAlerta(alertas[i].getId());
							
						}
					}
				}
			}
			AlertaService.this.stopSelf();
			
		}
	};
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		return START_STICKY;
	}
	

	private void crearNotificacion( double time, boolean vibrar, boolean sonar)
	{
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		
		int icon = R.drawable.ic_lock_idle_alarm;
		CharSequence tickerText = "Alerta Turno!";
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);
		
		Context context = getApplicationContext();
		CharSequence contentTitle = "Alerta!!";
		CharSequence contentText = "Faltan " + (time/60000) + " minutos para su turno";
		Intent notificationIntent = new Intent(this, VerTurnoActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		notification.defaults |= Notification.DEFAULT_LIGHTS;	
		
		if(sonar)
			notification.defaults |= Notification.DEFAULT_SOUND;
		if(vibrar)
		{
			long[] vibrate = {0,100,200,300,500};
			notification.vibrate = vibrate;
		}
		
		mNotificationManager.notify(ALERT_ID, notification);
		
	}
	
}
